package com.ying.core.exception;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.ying.Application;
import com.ying.core.response.ApiResponse;
import com.ying.core.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;


@RestControllerAdvice
public class GlobalExceptionHandling {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    @ExceptionHandler(value = CustomException.class)
    public ApiResponse processException(CustomException e) {
        log.error("位置:{} -> 错误信息:{}", e.getMethod() ,e.getLocalizedMessage());
        return ApiResponse.failure(Objects.requireNonNull(ResultCode.getByCode(e.getCode())));
    }

    @ExceptionHandler(value = NotRoleException.class)
    public ApiResponse processException(NotRoleException e) {
//        e.printStackTrace();
        return ApiResponse.failure(ResultCode.PERMISSION_NO_ACCESS);
    }

    @ExceptionHandler(value = NotPermissionException.class)
    public ApiResponse processException(NotPermissionException e) {
//        e.printStackTrace();
        return ApiResponse.failure(ResultCode.PERMISSION_NO_ACCESS);
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ApiResponse exception(Exception e) {
        e.printStackTrace();
        return ApiResponse.failure(ResultCode.UNKNOWN_EXCEPTION);
    }

}